<template>
  <b-container>
    <b-form @submit="onSubmit">
      <b-row>
        <b-col v-for="(group, idxx) in groupFormFields" :key="'g-'+idxx">
          <b-form-group
            v-for="(field, index) in group"
            :id="'input-group-'+index"
            :key="index"
            label-cols="2"
            :label="field.fieldName"
            :aria-required="field.required"
          >
            <b-form-radio-group v-if="field.type === 'radio'">
              <b-form-radio
                v-for="(r, idx) in field.valueRages"
                :key="idx"
                v-model="field.value"
                :required="field.required"
                :name="field.fieldName"
                :value="r"
              >{{ r }}</b-form-radio>
            </b-form-radio-group>
            <b-form-select v-else-if="field.type === 'selection'" v-model="field.value" :options="options(field)" />
            <b-form-input
              v-else
              :id="'input-'+index"
              v-model="field.value"
              :required="field.required"
              :placeholder="field.placeholder"
              :type="field.type"
            />
          </b-form-group>
        </b-col>
      </b-row>
      <button type="submit" class="btn btn-primary">提交</button>
    </b-form>
  </b-container>
</template>

<script>

import { getByScens, submitInfo } from '~/api/formConfig'

export default {
  name: 'Form',
  data() {
    return {
      formFileds: [
        { fieldName: '姓名', field: 'name', value: '', required: true, placeholder: '' },
        { fieldName: '年龄', field: 'age', value: '', required: true, placeholder: '' }
      ]
    }
  },
  computed: {
    options() {
      return (field) => {
        return field.valueRages.map(r => {
          return {
            name: r,
            value: r
          }
        })
      }
    },
    groupFormFields() {
      const res = [[], []]
      this.formFileds.forEach((item, index) => {
        res[index % 2].push(item)
      })
      return res
    }
  },
  created() {
    getByScens({
      scene: 'sign'
    }).then(r => {
      this.formFileds = r.data.items
    })
  },
  methods: {
    onSubmit(evt) {
      evt.preventDefault()
      const values = {}
      this.formFileds.forEach(field => {
        if (field.value) {
          values[field.field] = field.value
        }
      })
      const formData = {
        sceneCode: 'sign',
        values
      }
      submitInfo(formData)
        .then(() => {
          this.$router.push({ path: '/home' })
        })
    }
  }
}
</script>

<style scoped>

</style>
